package com.m3958.firstgwt.server.service;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.logging.Logger;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class WebCacherDiskFileImpl implements WebCacher{
	
	@Inject
	private SiteConfiger siteConfiger;
	
	@Inject
	private FilePathService fps;
	
	private Logger logger = Logger.getLogger(this.getClass().getName());

	@Override
	public void setItem(Integer siteId,String content,String uri, String... paraVals) {
		String croot = siteConfiger.getValue(SiteConfiger.SiteConfigerKeyName.SITE_CACHER_ROOT);
		File f = new File(croot);
		f = new File(f, String.valueOf(siteId));
		f = new File(f, "default");
		f = new File(f,uri);
		if(!f.exists()){
			boolean b = f.mkdirs();
			logger.info("making cache dir: " + String.valueOf(b));
		}
		String fname = "index.html";
		if(paraVals.length > 2){
			fname = "";
			for(String pv: paraVals){
				if(pv == null || pv.isEmpty())continue;
				fname += pv + ".";
			}
			fname = fname + "html";
		}
		f = new File(f,fname);
		
		try {
			fps.setContents(f, content, "UTF-8");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public String getItem(String... keys) {
		return null;
	}

	@Override
	public void clearAll(String siteId) {
		String croot = siteConfiger.getValue(SiteConfiger.SiteConfigerKeyName.SITE_CACHER_ROOT);
		File f = new File(croot);
		f = new File(f,siteId);
		fps.deleteDirectory(f);
	}

}
